#include "progress.h"
#include "read.h"
#include <iostream>

MainWindow::MainWindow()
:
m_VBox(Gtk::ORIENTATION_VERTICAL, 5),
m_pBox(Gtk::ORIENTATION_VERTICAL, 5),
Progress("Progress"),
Down("0 K"),
Speed_label("Speed :"),
Speed("0 B"),
m_Button_Close("Close"),
m_Button_Pause("Pause")
{
	set_default_size(400,-1);
	m_VBox.set_border_width(10);
	add(m_VBox);
	Progress.add(m_pBox);
	Down.set_justify(Gtk::JUSTIFY_LEFT);
	m_pBox.pack_start(Down);
	Speed_label.set_justify(Gtk::JUSTIFY_LEFT);
	m_pBox.pack_start(Speed_label);
	Speed.set_justify(Gtk::JUSTIFY_LEFT);
	m_pBox.pack_start(Speed);
	m_VBox.pack_start(Progress, Gtk::PACK_SHRINK, 5);
	m_VBox.pack_start(m_ProgressBar, Gtk::PACK_SHRINK, 5);
	

	Glib::signal_timeout().connect(sigc::mem_fun(*this, &MainWindow::on_timeout), 500 );
	m_VBox.pack_start(m_hBox);
	m_hBox.pack_start(m_Button_Pause);
    m_Button_Pause.signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_button_pause) );
	m_hBox.pack_start(m_Button_Close);
	m_Button_Close.signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_button_close) );
	m_Button_Close.set_can_default();
	m_Button_Close.grab_default();
	m_hBox.set_homogeneous();
	show_all_children();

}

void MainWindow::on_button_close()
{
	hide();
	//if(!("COMPLETE" == Speed.get_text()))
	//	exit(0);
	//else
	//{
	     system("pkill --signal SIGKILL aria2c");
	  //   exit(1);
	//}
}
bool MainWindow::on_timeout()
{
	int ret_val = read();
	if(1 == ret_val)
	{
	    m_Button_Pause.hide();
	    system("zenity --notification --text=\"Download Complete\" &");
	    return false;
	}
	if(3 == ret_val || 2 == ret_val )
	{
	    m_Button_Pause.hide();
	    system("zenity --notification --text=\"Download Error\" &");
	 	return false;   
	}
	
	return true;
}

void MainWindow::on_button_pause()
{
    if("Pause" == m_Button_Pause.get_label())
    {
        system("pkill --signal SIGSTOP aria2c");
        m_Button_Pause.set_label("Resume");
        //Speed.set_label("PAUSED");
    }
    else
    {
        system("pkill --signal SIGCONT aria2c");
        m_Button_Pause.set_label("Pause");
    }
}
